package com.zgt.dao.impl;

import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.zgt.dao.ResearchDao;
import com.zgt.model.Research;

@Repository("researchDao")
public class ResearchDaoImpl implements ResearchDao {

	private HibernateTemplate hibernateTemplate;

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	@Resource
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public void deleteResearchById(int id) {
		Research research = getResearchById(id);
		hibernateTemplate.delete(research);
	}

	public Research getResearchById(int id) {
		return hibernateTemplate.get(Research.class, id);
	}

	public void saveResearch(Research research) {
		hibernateTemplate.save(research);
	}

	public void updateResearch(Research research) {
		hibernateTemplate.update(research);
	}

	
	public boolean isExist(Research Research) {
		// TODO Auto-generated method stub
		return false;
	}

	public int getCount(String query) {
		List<Research> researchs = hibernateTemplate.find(query);
		return researchs.size();
	}

	public List<Research> listResearch(int pageStart, int pageSize) {
		List<Research> researchs = hibernateTemplate.findByCriteria(
				DetachedCriteria.forClass(Research.class), pageStart, pageSize);
		return researchs;
	}

	public void saveResearchs(List list) {
		Iterator it = list.iterator();
		while (it.hasNext()) {
			hibernateTemplate.save(it.next());
		}
	}

	@SuppressWarnings("unchecked")
	public List<Research> listSearch(final String query, final int start, final int size ) {
		List<Research> researchs = hibernateTemplate.executeFind(new HibernateCallback(){

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				return session.createQuery(query).setFirstResult(start).setMaxResults(size).list();
			}
			});
		return researchs;
	}

	public List<Research> listAllResearch() {
		return hibernateTemplate.find("from Research");
	}

	public int getCount() {
		List<Research> list = listAllResearch();
		return list.size();
	}

	
}
